﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ArrayUtil
{
    /// <summary>
    /// 交换数组内容
    /// 这种智能对数值类型进行交换
    /// </summary>
    /// <param name="arr">待交换的数组</param>
    public static void Swap(int[] arr)
    {
        // 为空或者少于两个节点则不需要交换 
        if (arr == null || arr.Length < 2)
        {
            return; 
        }

        // 使用异或进行交换
        for (int i = 0, j = arr.Length - 1; i < j; i++, j--)
        {
            arr[i] = arr[i] ^ arr[j];
            arr[j] = arr[i] ^ arr[j];
            arr[i] = arr[i] ^ arr[j];
        }
    }

    /// <summary>
    /// 支持任意类型的交换方法
    /// </summary>
    /// <typeparam name="T">泛型</typeparam>
    /// <param name="arr">泛型数组</param>
    public static void Swap<T>(T[] arr)
    {
        if (arr == null || arr.Length < 2)
        {
            return;
        }

        for (int i = 0, j = arr.Length - 1; i < j; i++, j--)
        {
            (arr[i], arr[j]) = (arr[j], arr[i]);
        }
    }

    /// <summary>
    /// 打印数组内容
    /// </summary>
    /// <param name="array">待打印的数组</param>
    public static void PrintArray(int[] array)
    {
        Console.WriteLine(string.Join(",", array));
    }

}
